package com.kingre.et.dao.jpa;

import java.util.List;

import org.apache.log4j.Logger;

import com.kingre.et.dao.IRawdataDAO;
import com.kingre.et.model.Rawdata;
import com.kingre.et.model.User;

public class RawdataDAOJPA extends GenericDAOJPA<Rawdata, Integer> implements IRawdataDAO {
    private static final Logger logger = Logger.getLogger(RawdataDAOJPA.class);

    @Override
    @SuppressWarnings("unchecked")
    public List<Rawdata> findByUser(User user) {
        return getJpaTemplate().find("FROM Rawdata p WHERE user = ? ORDER BY question.id", user);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Rawdata findByUserIndex(User user, int index) {
        List<Rawdata> rawdata = getJpaTemplate().find("FROM Rawdata p WHERE user = ? and question.id = ?", user, index);

        if (!rawdata.isEmpty()) {
            return rawdata.get(0);
        }
        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public int getVDValue(User user, int[] questionId) {
        String hql = "select sum(originalScore) from Rawdata where user = ? ";
        if (questionId != null) {
            hql += "and question.id in (";
            for (int i = 0; i < questionId.length; i++) {
                hql += (i == 0 ? questionId[i] : "," + questionId[i]);
            }
            hql += ")";
        }
        logger.debug("hql =" + hql);
        List list = getJpaTemplate().find(hql, user);
        return Integer.parseInt(list.get(0).toString());
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Rawdata> findAll() {
        return getJpaTemplate().find("FROM Rawdata p ORDER BY user.id, question.id");
    }

    @Override
    @SuppressWarnings("unchecked")
    public int getValue(User user, int questionId) {
        String hql = "FROM Rawdata where user = ? and question.id = ? ";
        List<Rawdata> list = getJpaTemplate().find(hql, user, questionId);
        return list.isEmpty() ? 0 : list.get(0).getOriginalScore();
    }

    @Override
    @SuppressWarnings("unchecked")
    public int getStandardScore(User user, int questionId) {
        String hql = "FROM Rawdata where user = ? and question.id = ? ";
        List<Rawdata> list = getJpaTemplate().find(hql, user, questionId);
        return list.isEmpty() ? 0 : list.get(0).getStandardScore();
    }
}
